package com.zhang.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class CookieUtils {


    //添加cookie
    public static void addCookie(String cookieName, HttpServletRequest req, HttpServletResponse rsp,String username,String password) {
        Cookie cookie = getCookie(cookieName, req);
        if(cookie != null){
            cookie.setValue(username+"#"+password);
        }else {
            try {
                cookie = new Cookie(cookieName, URLEncoder.encode(username,"UTF-8")+"#"+password);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }


        cookie.setPath(req.getContextPath());   //设置cookie的有效范围(当前项目)
        cookie.setMaxAge(7*24*60*60); //保存7天
        rsp.addCookie(cookie);        //添加到响应头中

    }

    //获取cookie
    public static Cookie getCookie(String cookieName,HttpServletRequest req){
        Cookie[] cookies = req.getCookies();
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals(cookieName)){
                return cookie;
            }
        }

        return null;
    }
}
